/**
 *
 */
package at.com.vn.chess.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.pojoxml.core.PojoXml;
import org.pojoxml.core.PojoXmlFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import at.com.vn.chess.entity.Entity;

/**
 * @author nghilt
 *
 */
public class XmlUtils<K extends Entity, V> {
	
	PojoXml pojoxml;
	public XmlUtils() {
		pojoxml = PojoXmlFactory.createPojoXml();		
		pojoxml.setOutputXmlFormat(false);
	}
	
	public String convertToXml(K obj, String processName) {
		obj.setProcessName(processName);
		return pojoxml.getXml(obj);
	}
	
	@SuppressWarnings("unchecked")
	public K convertToObject(String xml, Class<K> clazz1, Class<V> clazz2) {
		if(clazz2 != null) {
			pojoxml.addCollectionClass(clazz2.getSimpleName(), clazz2);			
		}
		return (K) pojoxml.getPojo(xml, clazz1);
	}
	
	public static String getProcessName(String xml) {
	      DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
	      domFactory.setNamespaceAware(true);
			try {
				DocumentBuilder builder = domFactory.newDocumentBuilder();
				InputStream is = new ByteArrayInputStream(xml.getBytes());
				Document doc = builder.parse(is);

				doc.getDocumentElement().normalize();
				String rootName = doc.getDocumentElement().getNodeName();
				NodeList rootNode = doc.getElementsByTagName(rootName);
				if(rootNode.getLength() > 0) {
					Node root = rootNode.item(0);
					NodeList elementNodes = root.getChildNodes();
					for (int i = 0; i < elementNodes.getLength(); i++) {
						Node node = elementNodes.item(i);
						if(node.getNodeName().equalsIgnoreCase("processName")) {
				            NodeList childNodes = node.getChildNodes();
				            for (int j = 0; j < childNodes.getLength(); j++ ) {
				                Node data = childNodes.item(j);
				                if ( data.getNodeType() == Node.TEXT_NODE )
				                    return data.getNodeValue();
				            }
				        }
					}
				}
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		    return "";
	   }
//	public static void main(String[] args) {
//		PlayersInfo player = new PlayersInfo();
//		player.setPlayer1Name("nghi");
//		player.setPlayer2Name("nhai");
//		String xml = convertToXml(player, "processName");
//		System.out.println(xml);
//		System.out.println(getProcessName(xml));
//	}
}